package com.hktf.uilib.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import com.permissionx.guolindev.PermissionX;
import com.permissionx.guolindev.callback.ExplainReasonCallbackWithBeforeParam;
import com.permissionx.guolindev.callback.ForwardToSettingsCallback;
import com.permissionx.guolindev.callback.RequestCallback;
import com.permissionx.guolindev.request.ExplainScope;
import com.permissionx.guolindev.request.ForwardScope;
import com.hktf.corelib.utils.LogMds;
import com.hktf.uilib.R;
import com.hktf.uilib.app.BaseActivity;
import com.hktf.uilib.utils.DlgUtils;
import com.hktf.uilib.widget.RequestPermissionDialog;

import java.lang.reflect.Method;
import java.util.List;

/**
 * @包名称： com.yx.uilib.utils
 * @类名： PermissionUtils
 * @创建人： 陈大专
 * @时间： 2020/09/10 9:49
 * @描述：权限工具类
 */
public class PermissionHelper {
    private static final String TAG="permission";

    /**
     * 悬浮窗权限检查
     * @param context
     * @return
     */
    public static boolean checkFloatPermission(Context context) {
        if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.M) {//6.0以上
            boolean result = false;
            try {
                Class clazz = Settings.class;
                Method canDrawOverlays = clazz.getDeclaredMethod("canDrawOverlays", Context.class);
                result = (boolean) canDrawOverlays.invoke(null, context);
                Log.e(TAG, "checkFloatPermission:-->" + result);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4-5.1
            return getAppOps(context);
        } else {//4.4以下
            return true;
        }
    }

    private static boolean getAppOps(Context context) {
        try {
            Object object = context.getSystemService(context.APP_OPS_SERVICE);
            if (object == null) {
                return false;
            }
            Class localClass = object.getClass();
            Class[] arrayOfClass = new Class[3];
            arrayOfClass[0] = Integer.TYPE;
            arrayOfClass[1] = Integer.TYPE;
            arrayOfClass[2] = String.class;
            Method method = localClass.getMethod("checkOp", arrayOfClass);
            if (method == null) {
                return false;
            }
            Object[] arrayOfObject1 = new Object[3];
            arrayOfObject1[0] = Integer.valueOf(24);
            arrayOfObject1[1] = Integer.valueOf(Binder.getCallingUid());
            arrayOfObject1[2] = context.getPackageName();
            int m = ((Integer) method.invoke(object, arrayOfObject1)).intValue();
            return m == AppOpsManager.MODE_ALLOWED;
        } catch (Exception e) {
            Log.e(TAG, "permissions judge: -->" + e.toString());
        }
        return false;
    }

    /**
     * 请求悬浮窗权限
     * @param activity
     * @param requestCode
     */
    public static void requestOverlayPermission(Activity activity,int requestCode){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//6.0以上
            try {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                intent.setData(Uri.parse("package:" + activity.getPackageName()));
                activity.startActivityForResult(intent, requestCode);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", activity.getPackageName(), null));
        }
    }

    /**
     * 安卓R(11)请求管理所有文件权限
     * @param activity
     * @param requestCode
     */
    public static void requestManageAllFiles(Activity activity,int requestCode){
        Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
        intent.setData(Uri.parse("package:" + activity.getPackageName()));
        try {
            activity.startActivityForResult(intent, requestCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean isServiceON(Context context,String className){
        ActivityManager activityManager = (ActivityManager)context.getSystemService(context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo>
                runningServices = activityManager.getRunningServices(100);
        if (runningServices.size() < 0 ){
            return false;
        }
        for (int i = 0;i<runningServices.size();i++){
            ComponentName service = runningServices.get(i).service;
            if (service.getClassName().contains(className)){
                return true;
            }
        }
        return false;
    }
    public static void gotoAccessibilitySet(Context context){
        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static void gotoSetting(final Context context,String msg){
        DlgUtils.showDlg(context, msg == null ? "请到设置页面打开相关权限" : msg, context.getString(R.string.ok),context.getString(R.string.cancel), new DlgUtils.MyListener() {
            @Override
            public void onConfirm() {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", context.getPackageName(), null);
                intent.setData(uri);
                context.startActivity(intent);
            }

            @Override
            public void onCancel() {

            }
        });

    }
    public static interface MyPermissionListener{
        void onSuccess();
        void onFail();
    }

    public static void check(BaseActivity context,MyPermissionListener listener,String tip1,String tip2,String... permissions){
        PermissionX.init(context)
                .permissions(
                        permissions
                )
                .explainReasonBeforeRequest()
                .onExplainRequestReason(new ExplainReasonCallbackWithBeforeParam() {
                    @Override
                    public void onExplainReason(ExplainScope scope, List<String> deniedList, boolean beforeRequest) {
                        scope.showRequestReasonDialog(new RequestPermissionDialog(context,tip1,tip2,deniedList));
                    }
                })
                .onForwardToSettings(new ForwardToSettingsCallback() {
                    @Override
                    public void onForwardToSettings(ForwardScope scope, List<String> deniedList) {
                        for (String str : deniedList) {
                            LogMds.d("hxwPer", "str " + str);
                        }
                        //                        if (myListener != null) {
                        //                            myListener.onFail();
                        //                        }
//                        scope.showForwardToSettingsDialog(deniedList, "您需要去设置中手动开启以下权限", "确定", "取消");
                        scope.showForwardToSettingsDialog(new RequestPermissionDialog(context,"缺少权限",
                                "您需要去设置中手动开启以下权限",deniedList));
                    }
                })
                .request(new RequestCallback() {
                    @Override
                    public void onResult(boolean allGranted, List<String> grantedList, List<String> deniedList) {
                        if (allGranted) {
                            if (listener != null) {
                                listener.onSuccess();
                            }
                        } else {
                            Toast.makeText(context, "您拒绝了应用申请权限", Toast.LENGTH_SHORT).show();
                            if (listener != null) {
                                listener.onFail();
                            }
                        }
                    }
                });
    }

}
